package com.ycrlkj.android.modulescore.main.activity.app;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.ycrlkj.android.modulesbase.libbase.utils.PhoneUtil;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.apiservice.NoauthApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityRegisterBinding;
import com.ycrlkj.android.modulescore.main.entity.User;
import com.ycrlkj.android.modulescore.main.viewmodel.RegisterViewModel;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_REGISTER)
public class RegisterActivity extends AppCompatActivity {

    private ActivityRegisterBinding binding;
    private RegisterViewModel viewModel;

    @Inject
    NoauthApiService noauthApiService;

    private Handler countDownHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(RegisterViewModel.class);
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);

        setContentView(binding.getRoot());
    }

    public void handleCallServicePhone(View view) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + getString(R.string.servicePhone)));
        startActivity(intent);
    }

    public void toLogin() {
        ARouter.getInstance().build(RoutePath.PAGE_LOGIN).navigation();
    }

    public void handleToLogin(View view) {
        toLogin();
    }

    public void handleRegister(View view) {
        String phone = viewModel.getPhone().getValue();
        String smsCode = viewModel.getSmsCode().getValue();

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong("手机号必须填写");
            return;
        }

        if (!PhoneUtil.isMobileNumberEasy(phone)) {
            ToastUtils.showLong("请填写正确的手机号");
            return;
        }


        if (TextUtils.isEmpty(smsCode)) {
            ToastUtils.showLong("验证码必须填写");
            return;
        }
        if (smsCode.length() != 4) {
            ToastUtils.showLong("验证码应为4位数字");
            return;
        }

        User form = new User();
        form.setPhone(phone);
        form.setPassword(smsCode);

        register(form);
    }


    @SuppressLint("CheckResult")
    public void register(User form) {
        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this);
        XPopupUtil.hideLoadingDelay(loadingPopupView);

        noauthApiService.register(form)
                .compose(ResponseTransformer.obtain())
                .subscribe(resultData -> {
                    XPopupUtil.hideLoading(loadingPopupView);

                    if (resultData.getStatus() == 0) {
                        XPopupUtil.showModal(RegisterActivity.this, "注册成功, 现在登录", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                finish();//先关闭自己, 否则按返回按钮时, 会返回到此页面
                                toLogin();
                            }
                        });
                    }else{
                        ToastUtils.showLong(resultData.getToast());
                    }

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(RegisterActivity.this, e);
                    }
                });

    }

    @SuppressLint("CheckResult")
    public void handleSendSmsCode(View view) {
        String phone = viewModel.getPhone().getValue();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong("手机号必须填写");
            return;
        }

        noauthApiService.sendSmsCode(phone)
                .compose(ResponseTransformer.obtain())
                .subscribe(resultData -> {
                    ToastUtils.showLong(resultData.getToast());

                    countDownHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Integer wait = viewModel.getSendSmsCodeWait().getValue();
                            wait--;
                            if (wait <= 0) {
                                viewModel.getSendSmsCodeWait().setValue(60);//重置 wait = 60
                            } else {
                                viewModel.getSendSmsCodeWait().setValue(wait);
                                countDownHandler.postDelayed(this, 1000);//调用自身
                            }
                        }
                    }, 1000);//每秒执行一次runnable

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(RegisterActivity.this, e);
                    }
                });

    }


}